package com.canyou.utils;

import org.joda.money.CurrencyUnit;
import org.joda.money.Money;

import java.math.BigDecimal;
import java.math.RoundingMode;

/**
 * money 操作类
 *
 * @author fy
 * @date 20/04/11 11:13
 */
public final class MoneyUtils {

    private MoneyUtils() {
    }

    private static final String CURRENCY_UNIT = "CNY";

    public static BigDecimal toBigDecimal(Money money) {
        if (money == null) {
            return null;
        }
        return money.getAmount();
    }

    public static Money parse(String moneyStr) {
        if (StringUtils.isBlank(moneyStr)) {
            return null;
        }
        return Money.of(CurrencyUnit.of(CURRENCY_UNIT), new BigDecimal(moneyStr.trim()), RoundingMode.HALF_UP);
    }

    public static Money parse(Integer moneyInt) {
        if (moneyInt == null) {
            return null;
        }
        return Money.of(CurrencyUnit.of(CURRENCY_UNIT), new BigDecimal(moneyInt), RoundingMode.HALF_UP);
    }

    public static Money parse(Long moneyLong) {
        if (moneyLong == null) {
            return null;
        }
        return Money.of(CurrencyUnit.of(CURRENCY_UNIT), new BigDecimal(moneyLong), RoundingMode.HALF_UP);
    }

    public static Money parse(Double moneyDouble) {
        if (moneyDouble == null) {
            return null;
        }
        return Money.of(CurrencyUnit.of(CURRENCY_UNIT), BigDecimal.valueOf(moneyDouble), RoundingMode.HALF_UP);
    }

    public static Money parse(Float moneyFloat) {
        if (moneyFloat == null) {
            return null;
        }
        return Money.of(CurrencyUnit.of(CURRENCY_UNIT), BigDecimal.valueOf(moneyFloat), RoundingMode.HALF_UP);
    }

    /**
     * 金额相加, money1不能为null
     *
     * @param money1
     * @param money2
     * @return
     */
    public static Money plus(Money money1, Money money2) {
        if (money2 == null) {
            return money1;
        } else {
            return money1.plus(money2);
        }
    }

}
